<script setup lang="ts">
import { addRoleAPI, editRoleAPI, getRolePermissionsAPI, permissionsTreeAPI } from '@/apis/systemRole';
import type { AddRoleParamsType,  permissionsTreeType } from '@/types/systemRole';
import { type FormRules, type FormInstance, ElMessage } from 'element-plus';
import type { TreeInstance } from 'element-plus/lib/components/index.js';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 步骤条控制 -----
const activeIndex = ref<number>(1) // 当前步骤条的索引

// 下一步
const goStep = async () => {
  if (activeIndex.value >= 3) return // 判断是否是最后一部

  if (activeIndex.value === 1) {
    await roleFormRef.value?.validate() // 校验表单
  } else if (activeIndex.value === 2) {
    if (roleParams.value.perms.flat().length === 0) return ElMessage.error('请选择权限') // 判断有没有选权限
  }
  
  activeIndex.value += 1
}
// 上一步
const backStep = () => {
  if (activeIndex.value <= 1) return
  activeIndex.value -= 1
}

// 获取权限树形数据 ----------
const permissionsTree = ref<permissionsTreeType[]>([])
const getPermissionsTree = async () => {
  const res = await permissionsTreeAPI()
  permissionsTree.value = res.data
}
getPermissionsTree()

const roleFormRef = ref<FormInstance>() // 表单ref
// 角色信息参数
const roleParams = ref<AddRoleParamsType>({
  perms: [],
  roleName: '',
  remark: ''
})
// 校验
const roleFormRules = ref<FormRules<AddRoleParamsType>>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ]
})

// 树形数据选中事件
const treeRefs = ref<TreeInstance[]>([]) // 树形数据ref 选择的
const plusTreeRefs = ref<TreeInstance[]>([]) // 树形数据ref 检查的
const treeCheck = () => {
  roleParams.value.perms = [] // 重置数组

  treeRefs.value.forEach((item, index) => {
    // 获取选中的keys
    const itemKeys = item.getCheckedKeys().map(item => +item)
    // 添加到数组中
    roleParams.value.perms.push(itemKeys)

    // 回显检查的树形数据
    plusTreeRefs.value[index].setCheckedKeys(itemKeys)
  })
}

const router = useRouter()
const route = useRoute()

// 编辑 -----------------------
// 获取角色详情
const getRoleDetail = async () => {
  const res = await getRolePermissionsAPI(route.params.id as string) // 获取角色详情
  console.log(res)
  // 回显数据
  roleParams.value.perms = res.data.perms
  roleParams.value.roleName = res.data.roleName
  roleParams.value.remark = res.data.remark
}
if (route.params.id) {
  getRoleDetail()
}

// 提交
const loadingFlag = ref(false)
const submitRole = async () => {
  loadingFlag.value = true
  try {
    if (!route.params.id) {
      // 新增角色
      await addRoleAPI(roleParams.value)
      ElMessage.success('添加成功')
    } else {
      // 编辑角色
      const res = await editRoleAPI(roleParams.value, +route.params.id)
      if (res.code === 10000) {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error(res.msg)
      }
    }
    router.back()
  } finally {
    loadingFlag.value = false
  }
}

</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header :content="!$route.params.id ? '添加角色' : '编辑角色'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeIndex">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <!-- 信息 -->
      <div class="form-container" v-show="activeIndex === 1">
        <div class="title">角色信息</div>
        <div class="role-form">
          <el-form ref="roleFormRef" class="form-box" :model="roleParams" :rules="roleFormRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleParams.roleName" />
            </el-form-item>
            <el-form-item label="* 角色描述" prop="remark">
              <el-input type="textarea" v-model="roleParams.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 权限 -->
      <div class="form-container" v-show="activeIndex === 2">
        <div class="title">权限配置</div>
        <div class="tree-wrapper">
          <div v-for="(item, index) in permissionsTree" :key="item.id" class="tree-item">
            <div class="tree-title"> {{ item.title }} </div>
            <el-tree
              :data="item.children"
              :props="{ label: 'title' }"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="treeRefs"
              @check="treeCheck()"
              :default-checked-keys="roleParams.perms[index]"
            />
          </div>
        </div>
      </div>
      <!-- 检查 -->
      <div class="form-container" v-show="activeIndex === 3">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleParams.roleName }}</div>
            <div class="form-item">角色描述：{{ roleParams.remark || '看来你比较懒' }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="(item, index) in permissionsTree" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="plusTreeRefs"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :props="{ label: 'title', disabled: () => true }"
                  :default-checked-keys="roleParams.perms[index]"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="backStep()" v-if="activeIndex > 1">上一步</el-button>
        <el-button type="primary" @click="goStep()" v-if="activeIndex < 3">下一步</el-button>
        <el-button type="primary" @click="submitRole" v-else :loading="loadingFlag">{{!$route.params.id ? '确认添加' : '确认编辑'}}</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px 5px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 0.5;
      height: 100%;
      background-color: #fff;
      overflow-y: auto;
      padding: 0 40px;
      margin: 0 auto;
      transform: translateX(-50px);
      
      .title {
        // height: 60px;
        // line-height: 60px;
        display: block;
        margin: 20px 0 30px;
        padding-left: 15px;
        margin-left: 10px;
        transform: translateX(-50px);
        border-left: 3px solid #4770ff;
      }

      .form {
        margin-bottom: 20px;
        // padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: start;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      // width: 32.3%;
      padding: 0px 4px 30px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>